package com.btex.app.treaty.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.btex.app.Config;
import com.btex.app.R;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Tools;
import com.btex.app.tools.Util;
import com.bumptech.glide.Glide;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.btex.app.R.id.dialog_traety_unwind_lin_price;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/10/15
 * @time 下午6:05
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */

public class UnwindDialog extends Dialog {


    @BindView(R.id.dialog_traety_unwind_imag_close)
    ImageView mDialogTraetyUnwindImagClose;
    @BindView(R.id.dialog_traety_unwind_ed_price)
    EditText mDialogTraetyUnwindEdPrice;
    @BindView(R.id.dialog_traety_unwind_ed_number)
    EditText mDialogTraetyUnwindEdNumber;
    @BindView(R.id.dialog_traety_unwind_tv_sure)
    TextView mDialogTraetyUnwindTvSure;
    @BindView(R.id.dialog_traety_unwind_tv_check)
    TextView mDialogTraetyUnwindTvCheck;
    @BindView(R.id.dialog_traety_unwind_tv_market)
    TextView mDialogTraetyUnwindTvMarket;
    @BindView(dialog_traety_unwind_lin_price)
    LinearLayout mDialogTraetyUnwindLinPrice;
    @BindView(R.id.dialog_traety_unwind_tv_price)
    TextView mDialogTraetyUnwindTvPrice;
    @BindView(R.id.dialog_traety_unwind_tv_number)
    TextView mDialogTraetyUnwindTvNumber;
    @BindView(R.id.duishou_price)
    RadioGroup mDuishouPrice;
    @BindView(R.id.baifen_bi)
    RadioGroup mBaifenBi;
    @BindView(R.id.dialog_traety_unwind_lin_number)
    LinearLayout mDialogTraetyUnwindLinNumber;
    @BindView(R.id.duishou_lin)
    LinearLayout duishou_lin;
    @BindView(R.id.jiazai)
    ImageView mJiazai;
    private String mDirection;
    private String mAmount;
    private String mLeverage;
    private String poPrice;
    private String mValuation;
    private String mSymbol;
    private String mContract_id;
    private String mIs_cross;
    private String mContract_anchor;
    private String mMSa_float_num;
    private MicroAVLIDialog mMicroAVLIDialog;
    private String mPrice;
    private String mNumber;
    private String mCheckType = "1";
    private String isLimit = "limit";

    private int beforeDot = 8;
    private int afterDot = 8;


    public UnwindDialog(@NonNull Context context, String direction, String amount, String leverage, String price, String valuation, String symbol, String contract_id, String is_cross, String Contract_anchor, String mSa_float_num) {
        super(context, R.style.coupon_style);
        mDirection = direction;
        mAmount = amount;
        mLeverage = leverage;
        poPrice = price;
        mValuation = valuation;
        mSymbol = symbol;
        mContract_id = contract_id;
        mIs_cross = is_cross;
        mContract_anchor = Contract_anchor;
        mMSa_float_num = mSa_float_num;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.unwind_dialog);
        ButterKnife.bind(this);

        Glide.with(getContext()).load(R.drawable.jiazai).into(mJiazai);
//        mDialogTraetyUnwindEdPrice.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(Integer.valueOf(mMSa_float_num))});
//        mDialogTraetyUnwindEdNumber.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(Integer.valueOf(mMSa_float_num))});


        initListener();

        mDialogTraetyUnwindTvPrice.setText(mSymbol);
//        mDialogTraetyUnwindTvNumber.setText(mContract_anchor);

//        String trim = Tools.round(Double.valueOf(poPrice), Integer.valueOf(mMSa_float_num)).toString().trim();
//        mDialogTraetyUnwindEdPrice.setText(trim);
        mDialogTraetyUnwindEdNumber.setText(mAmount);


        mMicroAVLIDialog = new MicroAVLIDialog(getContext());
        mDialogTraetyUnwindTvCheck.setSelected(true);


        //获取屏幕宽高
        DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
        //屏幕宽
        int widthPixels = displayMetrics.widthPixels;
        //屏幕高
        int heightPixels = displayMetrics.heightPixels;
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        //设置给attributes
        attributes.width = (int) (widthPixels * 0.9);
        attributes.height = (int) (heightPixels * 0.55);
        //让Dialog位置居中
        attributes.gravity = Gravity.CENTER;
        getWindow().setAttributes(attributes);
        //点击空白处不dismiss
        setCanceledOnTouchOutside(true);

        mDialogTraetyUnwindEdPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {
                mPrice = s.toString();
            }
        });

        mDialogTraetyUnwindEdNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mNumber = s.toString();
            }
        });

    }

    private void initListener() {

//        judge(mDialogTraetyUnwindEdPrice.getEditableText());
//        judge(mDialogTraetyUnwindEdNumber.getEditableText());

        mDialogTraetyUnwindEdPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                judge(s);

            }
        });


        mDialogTraetyUnwindEdNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                judge(s);

            }
        });


        mDialogTraetyUnwindEdPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mDialogTraetyUnwindLinPrice.setBackground(getContext().getResources().getDrawable(R.drawable.shape_otc_rd_selec_doub));
                } else {
                    mDialogTraetyUnwindLinPrice.setBackground(getContext().getResources().getDrawable(R.drawable.shape_otc_ed));
                }
            }
        });


        mDialogTraetyUnwindEdNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mDialogTraetyUnwindLinNumber.setBackground(getContext().getResources().getDrawable(R.drawable.shape_otc_rd_selec_doub));
                } else {
                    mDialogTraetyUnwindLinNumber.setBackground(getContext().getResources().getDrawable(R.drawable.shape_otc_ed));
                }
            }
        });


        mDuishouPrice.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.duishou_price_one:
                        if (mDirection.equals("1")) {
//                            做空
                            String trim1 = Tools.round(Double.valueOf(Config.BUY_YI), Integer.valueOf(mMSa_float_num)).toString().trim();
                            mDialogTraetyUnwindEdPrice.setText(trim1);

                        } else {
//                            做多
                            String trim1 = Tools.round(Double.valueOf(Config.SELL_YI), Integer.valueOf(mMSa_float_num)).toString().trim();
                            mDialogTraetyUnwindEdPrice.setText(trim1);
                        }

                        break;
                    case R.id.duishou_price_two:
                        String trim1 = Tools.round(Double.valueOf(Config.BUY_YI), Integer.valueOf(mMSa_float_num)).toString().trim();
                        mDialogTraetyUnwindEdPrice.setText(trim1);
                        break;

                    case R.id.duishou_price_three:

                        String trim = Tools.round(Double.valueOf(Config.SELL_YI), Integer.valueOf(mMSa_float_num)).toString().trim();

                        mDialogTraetyUnwindEdPrice.setText(trim);

                        break;
                }
            }
        });


        mBaifenBi.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

                switch (checkedId) {
                    case R.id.baifen_bi_one:
                        if (!TextUtils.isEmpty(mAmount)) {

                            Double aDouble = Double.valueOf(mAmount);
                            String trim = Tools.round(aDouble * 0.25, 4).toString().trim();
                            double floor = Math.floor(Double.valueOf(trim));
                            mDialogTraetyUnwindEdNumber.setText(String.valueOf((int) floor));
                        }
                        break;
                    case R.id.baifen_bi_two:
                        if (!TextUtils.isEmpty(mAmount)) {
                            Double aDouble = Double.valueOf(mAmount);
                            String trim = Tools.round(aDouble * 0.5, 4).toString().trim();
                            double floor = Math.floor(Double.valueOf(trim));
                            mDialogTraetyUnwindEdNumber.setText(String.valueOf((int) floor));
                        }
                        break;
                    case R.id.baifen_bi_three:

                        if (!TextUtils.isEmpty(mAmount)) {
                            Double aDouble = Double.valueOf(mAmount);
                            String trim = Tools.round(aDouble * 0.75, 4).toString().trim();
                            double floor = Math.floor(Double.valueOf(trim));
                            mDialogTraetyUnwindEdNumber.setText(String.valueOf((int) floor));
                        }
                        break;
                    case R.id.baifen_bi_four:
                        if (!TextUtils.isEmpty(mAmount)) {
                            Double aDouble = Double.valueOf(mAmount);
                            String trim = Tools.round(aDouble * 1, 4).toString().trim();
                            double floor = Math.floor(Double.valueOf(trim));
                            mDialogTraetyUnwindEdNumber.setText(String.valueOf((int) floor));
                        }
                        break;
                }
            }
        });
    }

    @OnClick({R.id.dialog_traety_unwind_imag_close, R.id.dialog_traety_unwind_tv_check, R.id.dialog_traety_unwind_tv_market, R.id.dialog_traety_unwind_tv_sure_lin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dialog_traety_unwind_imag_close:
                dismiss();
                break;
            case R.id.dialog_traety_unwind_tv_check:
                isLimit = "limit";
                mCheckType = "1";
                mDialogTraetyUnwindLinPrice.setVisibility(View.VISIBLE);
                duishou_lin.setVisibility(View.VISIBLE);
                SetStat();
                mDialogTraetyUnwindTvCheck.setSelected(true);

                break;
            case R.id.dialog_traety_unwind_tv_market:
                isLimit = "market";
                mCheckType = "2";
                mDialogTraetyUnwindLinPrice.setVisibility(View.GONE);
                duishou_lin.setVisibility(View.GONE);
                SetStat();
                mDialogTraetyUnwindTvMarket.setSelected(true);
                break;
            case R.id.dialog_traety_unwind_tv_sure_lin:

                mDialogTraetyUnwindTvSure.setClickable(false);
                if (mCheckType.equals("1")) {

                    String num = mDialogTraetyUnwindEdNumber.getText().toString().trim();
                    String price = mDialogTraetyUnwindEdPrice.getText().toString().trim();
                    if (!TextUtils.isEmpty(num) && !TextUtils.isEmpty(price)) {
                        if (mDirection.equals("1")) {
                            setContractorders(price, num, "-1");
                        } else {
                            setContractorders(price, num, "1");
                        }


                    } else {
                        Toast.makeText(getContext(), "请输入完整", Toast.LENGTH_SHORT).show();
                    }

                } else {

                    String trim = mDialogTraetyUnwindEdNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(trim)) {

                        if (mDirection.equals("1")) {
                            setContractorders(mPrice, trim, "-1");
                        } else {
                            setContractorders(mPrice, trim, "1");
                        }

                    } else {
                        Toast.makeText(getContext(), "请输入数量", Toast.LENGTH_SHORT).show();
                    }

                }


                break;
        }
    }


    public void SetStat() {
        mDialogTraetyUnwindTvCheck.setSelected(false);
        mDialogTraetyUnwindTvMarket.setSelected(false);
    }


    private void setContractorders(String treatyPrice, String treatyNumber, String type) {

        mDialogTraetyUnwindTvSure.setClickable(true);
        mJiazai.setVisibility(View.VISIBLE);

        String is_cross;

        Double aDouble = Double.valueOf(mLeverage);
        String trim = Tools.round(aDouble, 1).toString().trim();
        if (trim.equals("-1.0")) {
            trim = "-1";
            is_cross = "1";
        } else {
            is_cross = "-1";
        }

        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getContext());
        String token = sharedPreferences.getString(Config.TOKEN, null);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getContext(), sharedPreferences);
        RequestParams params = new RequestParams();
        params.addBodyParameter("contract_id", mContract_id);
        params.addBodyParameter("price", treatyPrice);
        params.addBodyParameter("amount", treatyNumber);
        params.addBodyParameter("leverage", trim);
        params.addBodyParameter("direction", type);
        params.addBodyParameter("type", isLimit);
        params.addBodyParameter("is_cross", mIs_cross);
        params.addBodyParameter("source", "android");

        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.PLACE_ORDER, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Log.i("nbshiowuerfhur", responseInfo.result);

                mJiazai.setVisibility(View.GONE);

                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result);
                    if (jsonObject.getString("code").equals("1")) {
                        dismiss();
                        Toast.makeText(getContext(), "操作成功", Toast.LENGTH_SHORT).show();
                    } else {
//                        Snackbar snackbar = Util.ShortSnackbar(mDialogTraetyUnwindTvSure, jsonObject.getString("info"), Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                        snackbar.show();
                        Util.showSnachBarDialog(mDialogTraetyUnwindEdPrice, getContext().getResources().getColor(R.color.red), jsonObject.getString("info"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }

        });

    }

    private void judge(Editable editable) {
        String temp = editable.toString();
        int posDot = temp.indexOf(".");
        //直接输入小数点的情况
        if (posDot == 0) {
            editable.insert(0, "0");
            return;
        }
        //连续输入0
        if (temp.equals("00")) {
            editable.delete(1, 2);
            return;
        }
        //输入"08" 等类似情况
        if (temp.startsWith("0") && temp.length() > 1 && (posDot == -1 || posDot > 1)) {
            editable.delete(0, 1);
            return;
        }

        //不包含小数点 不限制小数点前位数
        if (posDot < 0 && beforeDot == -1) {
            //do nothing 仅仅为了理解逻辑而已
            return;
        } else if (posDot < 0 && beforeDot != -1) {
            //不包含小数点 限制小数点前位数
            if (temp.length() <= beforeDot) {
                //do nothing 仅仅为了理解逻辑而已
            } else {
                editable.delete(beforeDot, beforeDot + 1);
            }
            return;
        }

        //如果包含小数点 限制小数点后位数
        if (temp.length() - posDot - 1 > afterDot && afterDot != -1) {
            editable.delete(posDot + afterDot + 1, posDot + afterDot + 2);//删除小数点后多余位数
        }
    }
}
